import OpenGL.GL as gl
import numpy as np
from pygl.rendertexture2d import RenderTexture2D
from pygl.renderbufferobject import RenderBufferObject

class FrameBufferObject:
    def __init__(self, width:int, height:int) -> None:
        fbo = np.empty(1, gl.GLuint)
        gl.glCreateFramebuffers(1, fbo)
        self.fbo_id = fbo[0]
        self.resize(width, height)

    def bind(self) -> None:
        gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, self.fbo_id)

    @staticmethod
    # 绑定到默认帧缓存
    def bindDefault() -> None:
        gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, 0)

    def delete(self) -> None:
        if gl.glIsFramebuffer(self.fbo_id):
            gl.glDeleteFramebuffers(1, self.fbo_id)

    def attachTexture2D(self, attachment: int, texture: RenderTexture2D, 
                        level: int) -> None:
        gl.glNamedFramebufferTexture(
            self.fbo_id, attachment, texture.tex_id, level)

    def isComplete(self) -> bool:
        return (gl.glCheckNamedFramebufferStatus(self.fbo_id, 
                gl.GL_FRAMEBUFFER) == gl.GL_FRAMEBUFFER_COMPLETE)
    
    def resize(self, width:int, height:int) -> None:
        self.width = width
        self.height = height

    def BlitDefault(self, mask:int, filter:int) -> None:
        gl.glBlitNamedFramebuffer(self.fbo_id, 0,
            0, 0, self.width, self.height, 0, 0, self.width, self.height, 
            mask, filter)

    def attachRenderbuffer(self, attachment: int, renderbuffertarget:int, 
                           renderbuffer: RenderBufferObject) -> None:
        gl.glNamedFramebufferRenderbuffer(self.fbo_id, attachment, 
                                renderbuffertarget, renderbuffer.rbo_id)
